package controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        Class<? extends BaseServlet> aClass = this.getClass();
        Method method;
        try{
            method = aClass.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(aClass.newInstance(), req, resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    protected Map<String,String> getParams(HttpServletRequest req){
        HashMap<String, String> map = new HashMap<>();
        Map<String, String[]> parameterMap = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entries = parameterMap.entrySet();
        for(Map.Entry<String, String[]> entry : entries){
            String[] value = entry.getValue();
            if(value.length > 1){
                map.put(entry.getKey(), Arrays.toString(value));
            }else{
                map.put(entry.getKey(), value[0]);
            }
        }
        return map;
    }
}
